import React, { useEffect } from 'react';
import { Button, ConfigProvider, DatePicker, message, Modal, Select, Space } from 'antd';
import TRNotification from '#/utils/notification';
import { TjChart } from '@/pages/ETrade/components';
import styles from './index.less';
import {
  postFindQuoteStationData,
  postQueryLastQuoteStation,
  postQueryRateData,
} from '../../service';
import TjTable from '@/pages/ETrade/components/TjTable';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import { useSetState } from 'ahooks';
import moment from 'moment';
import { HttpCode } from '#/utils/contacts';
import { tableColumn, getOptions } from './helper.';
import { TIME_96 } from '../../../components/helper.js';
import { PageLoading } from '@/components';

const StrategyCitationModalComponent = (props) => {
  const { onPress, searchForm, menuCode } = props;

  const [state, setState] = useSetState({
    nowStationId: '',
    date: moment(searchForm.calendarDate),
    stationOptions: [],
    dataList: [],
    dataSourceList: [],
    chartOptions: {},
    loading: true,
  });

  const _onCancel = () => {
    onPress({ index: 0 });
  };

  const getTableData = async (stationId) => {
    const res = await postQueryRateData({
      ...searchForm,
      reset: 0,
      stationId: stationId ? stationId : state.nowStationId,
      calendarDate: state.date.format('YYYYMMDD'),
    });
    if (res.statusCode === HttpCode.SUCCESS) {
      let dataList = res?.data?.dataList || [];
      const chartOptions = getOptions(dataList);
      const dataSourceList = res?.data?.dataSourceList || [];
      dataList = dataList.map((i) => ({
        ...i,
        dataSourceName: dataSourceList.find((d) => d.dataSourceId === i.dataSourceId)
          ?.dataSourceName,
        time: TIME_96[i.beginIndex] + '-' + TIME_96[i.endIndex],
      }));
      setState({
        dataList,
        dataSourceList,
        chartOptions,
        loading: false,
      });
    } else {
      message.info(res?.message || '获取数据失败');
    }
  };

  const init = async () => {
    // 查询上次交易单元    查询引用结算单元集合
    const services = [
      postQueryLastQuoteStation({
        marketId: searchForm.marketId,
        saveType: searchForm.saveType,
      }),
      postFindQuoteStationData({
        menuCode,
        stationId: searchForm.stationId,
      }),
    ];
    const [res1, res2] = await Promise.all(services);
    let nowStationId = searchForm.stationId;
    if (res1.statusCode === HttpCode.SUCCESS) {
      nowStationId = res1?.data;
    } else {
      message.info(res1?.message || '获取上次交易中心失败');
    }
    if (res2.statusCode === HttpCode.SUCCESS) {
      // 如果几个钟有这个场站则赋值当前场站，若没有默认第一个场站
      const stationOptions =
        res2?.data?.map((i) => ({ ...i, label: i.stationName, value: i.stationId.toString() })) ||
        [];
      const data = stationOptions.find((i) => i.value === searchForm.stationId) || null;
      nowStationId = nowStationId ? nowStationId : data?.value || stationOptions?.[0]?.value;
      setState({
        nowStationId,
        stationOptions,
      });
      // 用当前的场站去查询表格数据并绘制图
    } else {
      message.info(res2?.message || '获取引用结算单元集合失败');
    }
    await getTableData(nowStationId);
    setState({
      loading: false,
    });
  };

  useEffect(() => {
    (async () => {
      await init();
      // 查询引用的交易单元列表
    })();
  }, []);

  const handleSubmit = async () => {
    setState({
      loading: true,
    });
    await getTableData();
  };

  const _onOk = () => {
    onPress({
      index: 1,
      dataList: state.dataList,
      quoteStationId: state.nowStationId,
    });
  };

  return (
    <ConfigProvider locale={zh_CN}>
      <Modal
        width="80%"
        centered
        maskClosable={false}
        visible={true}
        confirmLoading={state.loading}
        title={<div>策略引用</div>}
        onCancel={_onCancel}
        onOk={_onOk}
      >
        <div className={styles.body}>
          {state.loading ? (
            <PageLoading />
          ) : (
            <>
              <Space>
                <Select
                  placeholder="请选择"
                  style={{ width: 200 }}
                  value={state.nowStationId}
                  options={state.stationOptions}
                  onChange={(v) =>
                    setState({
                      nowStationId: v,
                    })
                  }
                />
                <DatePicker
                  value={state.date}
                  onChange={(v) => {
                    setState({ date: v });
                  }}
                />
                <Button type="primary" onClick={handleSubmit}>
                  查询
                </Button>
              </Space>
              <div className={styles.content}>
                <div className={styles.contentLeft}>
                  <TjChart option={state.chartOptions} />
                </div>
                <div className={styles.contentRight}>
                  <TjTable columns={tableColumn} dataSource={state.dataList} />
                </div>
              </div>
            </>
          )}
        </div>
      </Modal>
    </ConfigProvider>
  );
};

class StrategyCitationModal {
  __key__ = '';

  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <StrategyCitationModalComponent
            {...props}
            onPress={(result) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new StrategyCitationModal();
